import Vue from 'vue'
import VueRouter from 'vue-router'

// 导入组件
import Tab from '@/pages/Tab'
import Cate from '@/pages/index/Cate'
import Index from '@/pages/tab/Index'
import Car from '@/pages/tab/Car'
import My from '@/pages/tab/My'
import Sel from '@/pages/tab/Sel'
import Det from '@/pages/common/Det'
import Login from '@/pages/Login'
import Addr from '@/pages/common/Addr'
import Order from '@/pages/my/Order'

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) {
    return originalPush.call(this, location, onResolve, onReject)
  }
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    {
      path: '/',
      redirect: '/tab'
    },
    {
      path: '/tab',
      component: Tab,
      children: [
        {
          path: '/tab',
          redirect: 'index'
        },
        {
          path: 'index',
          component: Index
        },
        {
          path: 'car',
          component: Car
        },
        {
          path: 'my',
          component: My
        },
        {
          path: 'sel',
          component: Sel
        }
      ]
    },
    {
      path: '/cate',
      component: Cate
    },
    {
      path: '/det',
      component: Det
    },
    {
      path: '/login',
      component: Login
    },
    {
      path: '/addr',
      component: Addr
    },
    {
      path: '/order',
      component: Order
    }
  ]
})

const arr = ['/det', '/tab/car']

router.beforeEach((to, from, next) => {
  const userinfo = sessionStorage.getItem('userinfo')
  if (arr.includes(to.path)) {
    if (userinfo) {
      next()
    } else {
      next('/login')
    }
  } else {
    next()
  }
})

export default router
